import * as echarts from 'echarts'
import proces from './process.vue'
import { connectWebSocket } from '@/utils/web-socket.js'
import { callRwghmxApi, updateRwghmxApi, saveAsRwghmxApi } from '../api/index'
import Flow from '@/views/components/flow.vue'
import { areAllFieldsEmpty } from '@/utils/index'
import SaveModel from '@/views/components/model/mission.vue'

export default {
  components: {
    proces,
    Flow,
    SaveModel
  },
  data() {
    return {
      formInline: {
        demand: '',
        targetArea: '',
        sample: ''
      },
      labelPosition: 'right',
      dialogTitle: '',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      },
      tableData: [],
      currentPage3: 1,
      trainId: '',
      test: '',
      socketUrl: window.ipConfig.decision,
      countpush: 0,
      chartDataX: [],
      TrainingsetList: [],
      TrainingTime: '',
      znjcJsonStr: {
        rwwcl: '',
        gcsxxjz: '',
        gcsxxfc: '',
        wxfzjh: '',
        cbjjz: '',
        cbjfc: '',
        tygdjjz: '',
        tygdjfc: ''
      },
      footerdata: {
        rwwcl: '',
        gcsxxjz: '',
        gcsxxfc: '',
        wxfzjh: '',
        cbjjz: '',
        cbjfc: '',
        tygdjjz: '',
        tygdjfc: ''
      },
      startMxStaut: false,
      trainName: '',
      testName: '',
      isModelSave: true,
      Mask: undefined
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.initCharts(
      'charts-line',
      'rgba(133, 141, 200, 1)',
      ['1', '2', '3', '4', '5', '6', '7'],
      ['rgba(90, 98, 159, 0)', 'rgba(133, 141, 200, 0.89)'],
      [140, 232, 101, 264, 90, 340, 250],
      '训练集',
      '(损失)'
    )
    // 在此调用算法模型
    this.connectWs()
  },
  methods: {
    /** 接受子组件按钮回调 */
    missionCallback(value, radioValue) {
      if (radioValue == 1) {
        // 保存逻辑
        updateRwghmxApi(value).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
          } else {
            this.$message.error('操作失败')
          }
        })
      } else {
        // 另存为逻辑
        saveAsRwghmxApi(value).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
          } else {
            this.$message.error('操作失败')
          }
        })
      }
    },
    // 模型保存
    handleModalSave() {
      if (this.isModelSave == true) {
        return this.$message.warning('请先训练')
      }
      this.$refs.modelRef.openModal(this.footerdata)
    },
    // 指标shu配置回调
    weightCallback(list) {
      let arr = list
      const obj = this.znjcJsonStr

      arr.forEach((item, index) => {
        let objKey = Object.keys(obj)[index] // 获取对象的键名（基于索引）
        let objValue = item.value // 获取对应的值
        obj[objKey] = Number(objValue) // 将对象的值添加到数组元素中
      })

      this.znjcJsonStr = obj
    },
    /** 打开指标树配置 */
    handleIndicatorWeight() {
      this.$refs.flowPath.dialogVisible = true
    },

    /** 训练及评估 */
    startedTraining() {
      if (
        !this.test ||
        this.test === '' ||
        !this.trainId ||
        this.trainId === ''
      ) {
        this.$message.warning('请将参数配置完整！')
        return
      }
      if (areAllFieldsEmpty(this.znjcJsonStr)) {
        this.$message.warning('请配置指标权重')
        return
      }
      this.Mask = this.$loading({
        lock: true,
        text: '模型训练中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 调用接口
      const params = {
        csjbh: this.test,
        xljBh: this.trainId,
        mxID: this.$route.query.id,
        znjcJsonStr: JSON.stringify(this.znjcJsonStr).replace(/\"/g, "'")
      }
      if (params.csjbh && params.xljBh && params.mxID && params.znjcJsonStr) {
        callRwghmxApi(params).then(response => {
          if (response.data.code !== 200) {
            this.Mask.close()
            return this.$message.error(response.data.msg)
          }
        })
      } else {
        return this.$message.error('请选择训练集和测试集以及配置权重')
      }
    },
    connectWs() {
      connectWebSocket({
        url: window.ipConfig.wsUrl,
        topic: [
          // 订阅任务规划模型训练集
          {
            name: '/topic/rwghmxUdpData',
            callback: res => {
              this.Mask.close()
              this.startMxStaut = true
              const datalist = JSON.parse(res.body)
              if (Array.isArray(datalist)) {
                // 处理训练集
                if (datalist.length != 0 && datalist[0]) {
                  // 去重
                  if (this.chartDataX.length < datalist[0]) {
                    this.chartDataX.push(datalist[0])
                    this.TrainingsetList.push(datalist[1])
                    this.initCharts(
                      'charts-line',
                      'rgba(133, 141, 200, 1)',
                      this.chartDataX,
                      ['rgba(90, 98, 159, 0)', 'rgba(133, 141, 200, 0.89)'],
                      this.TrainingsetList,
                      '训练集',
                      '(损失)'
                    )
                  }
                }
              } else if (typeof datalist === 'object') {
                this.footerdata = {
                  rwwcl: datalist.rwwcl,
                  gcsxxjz: datalist.gcsxxjz,
                  gcsxxfc: datalist.gcsxxfc,
                  wxfzjh: datalist.wxfzjh,
                  cbjjz: datalist.cbjjz,
                  cbjfc: datalist.cbjfc,
                  tygdjjz: datalist.tygdjjz,
                  tygdjfc: datalist.tygdjfc,
                  final: datalist.final
                }
                this.startMxStaut = false
                this.isModelSave = false
                // 置空，以防下次训练导致图表数据跳动
                this.chartDataX = []
                this.TrainingsetList = []
              }
            }
          }
        ]
      })
    },
    completeCallback(value) {
      if (value.type === 1) {
        this.trainName = value.data[0].jcybjID
        this.trainId = value.data[0].id
      } else {
        this.testName = value.data[0].jcybjID
        this.test = value.data[0].id
      }
    },
    onSubmit(text) {
      this.$refs.procesRef.dialogVisible = true
      this.dialogTitle = typeof text === 'string' ? text : '对话框'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },
    goBack() {
      this.$router.go(-1)
    },
    initCharts(
      eleId,
      color,
      xAxisData,
      seriesColor,
      seriesData,
      titleName,
      yAxisName
    ) {
      let chartDom = document.getElementById(eleId)
      let myChart = echarts.init(chartDom)
      let option = {
        color: [color],
        title: {
          text: titleName,
          textStyle: {
            color: '#fff',
            fontSize: 16
          },
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#fff'
            }
          }
        },
        legend: {
          show: false
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '10',
          right: '10',
          bottom: '0',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: xAxisData,
            axisLine: {
              lineStyle: {
                color: '#677488'
              }
            },
            axisLabel: {
              textStyle: {
                color: '#fff'
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: yAxisName,
            nameTextStyle: {
              color: '#fff',
              align: 'right'
            },
            splitLine: { show: false },
            axisLine: {
              lineStyle: {
                color: '#677488'
              }
            },
            axisLabel: {
              textStyle: {
                color: '#fff'
              }
            }
          }
        ],
        series: [
          {
            name: 'Line 1',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: seriesColor[1]
                },
                {
                  offset: 1,
                  color: seriesColor[0]
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: seriesData
          }
        ]
      }
      myChart.setOption(option)
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    }
  }
}
